<template>
  <div class="move-container">
    <Header title="移动文件" show-back />

    <div class="move-content">
      <!-- 待移动文件信息 -->
      <div v-if="fileToMove" class="file-info-card">
        <div class="card-header">
          <h3>待移动的文件</h3>
        </div>
        <div class="file-item">
          <div class="file-icon">
            <van-icon
              :name="getFileIcon(fileToMove)"
              :color="getFileIconColor(fileToMove)"
              size="24"
            />
          </div>
          <div class="file-details">
            <div class="file-name">{{ fileToMove.fileName }}</div>
            <div class="file-meta">
              <span v-if="!fileToMove.isFolder && fileToMove.fileSize">
                {{ formatFileSize(fileToMove.fileSize) }}
              </span>
              <span>{{ formatTime(fileToMove.updateTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 目标位置选择 -->
      <div class="target-section">
        <div class="section-header">
          <h3>选择目标位置</h3>
          <span class="current-path">{{ getCurrentPath() }}</span>
        </div>

        <!-- 面包屑导航 -->
        <div v-if="breadcrumbList.length > 0" class="breadcrumb">
          <div class="breadcrumb-wrapper">
            <span class="breadcrumb-item" @click="navigateToRoot">
              <van-icon name="home-o" />
              根目录
            </span>
            <template v-for="(item, index) in breadcrumbList" :key="item.id">
              <van-icon name="arrow" class="breadcrumb-separator" />
              <span
                class="breadcrumb-item"
                :class="{ active: index === breadcrumbList.length - 1 }"
                @click="navigateToFolder(item.id)"
              >
                {{ item.name }}
              </span>
            </template>
          </div>
        </div>

        <!-- 文件夹列表 -->
        <div class="folder-list">
          <van-loading v-if="loading" />

          <div v-else>
            <!-- 返回上级目录 -->
            <div
              v-if="currentFolderId !== 0"
              class="folder-item back-item"
              @click="goBack"
            >
              <van-icon name="arrow-left" size="20" />
              <span>返回上级目录</span>
            </div>

            <!-- 文件夹列表 -->
            <div
              v-for="folder in folderList"
              :key="folder.id"
              class="folder-item"
              :class="{ disabled: folder.id === fileToMove?.id || folder.id === fileToMove?.parentId }"
              @click="enterFolder(folder)"
            >
              <van-icon name="folder-o" color="#1989fa" size="20" />
              <span>{{ folder.fileName }}</span>
              <van-icon name="arrow" class="arrow-icon" />
            </div>

            <!-- 空状态 -->
            <div v-if="folderList.length === 0" class="empty-folders">
              <van-empty
                image="default"
                description="当前目录下没有文件夹"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 移动确认 -->
      <div class="move-actions">
        <div class="target-info">
          <span class="label">移动到：</span>
          <span class="path">{{ getCurrentPath() }}</span>
        </div>
        <van-button
          type="primary"
          block
          :disabled="!canMove"
          :loading="moving"
          @click="handleMove"
        >
          确认移动
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showConfirmDialog } from 'vant'
import Header from '@/components/Header.vue'
import { useFileStore } from '@/stores/file'
import { moveFile } from '@/api/file'
import type { FileInfo } from '@/api/file'

const router = useRouter()
const route = useRoute()
const fileStore = useFileStore()

// 状态
const loading = ref(false)
const moving = ref(false)
const fileToMove = ref<FileInfo | null>(null)
const folderList = ref<FileInfo[]>([])
const currentFolderId = ref(0)
const breadcrumbList = ref<{ id: number; name: string }[]>([])

// 计算属性
const canMove = computed(() => {
  if (!fileToMove.value) return false

  // 不能移动到自己的子目录或当前目录
  return currentFolderId.value !== fileToMove.value.parentId
})

// 方法
const { formatFileSize, formatTime } = fileStore

const getFileIcon = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return 'folder-o'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'photo-o'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return 'video-o'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return 'music-o'
    case 'pdf':
      return 'description'
    case 'doc':
    case 'docx':
      return 'description'
    case 'xls':
    case 'xlsx':
      return 'description'
    case 'ppt':
    case 'pptx':
      return 'description'
    case 'txt':
      return 'notes-o'
    case 'zip':
    case 'rar':
    case '7z':
      return 'bag-o'
    default:
      return 'description'
  }
}

const getFileIconColor = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return '#1989fa'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return '#ff976a'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return '#ff976a'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return '#07c160'
    case 'pdf':
      return '#ee0a24'
    case 'doc':
    case 'docx':
      return '#1989fa'
    case 'xls':
    case 'xlsx':
      return '#07c160'
    case 'ppt':
    case 'pptx':
      return '#ff976a'
    default:
      return '#969799'
  }
}

const getCurrentPath = () => {
  if (currentFolderId.value === 0) {
    return '根目录'
  }

  let path = '根目录'
  breadcrumbList.value.forEach(item => {
    path += ` / ${item.name}`
  })
  return path
}

const loadFileInfo = () => {
  const fileId = parseInt(route.query.fileId as string)

  if (!fileId) {
    showToast('文件ID参数错误')
    router.back()
    return
  }

  // 从文件列表中查找文件信息
  const { fileList } = fileStore
  const file = fileList.find(f => f.id === fileId)

  if (file) {
    fileToMove.value = file
    // 初始化当前目录为文件当前所在目录，方便用户理解当前位置
    currentFolderId.value = file.parentId
  } else {
    showToast('文件不存在')
    router.back()
  }
}

const loadFolderList = async (folderId = currentFolderId.value) => {
  try {
    loading.value = true

    const response = await fileStore.fetchFileList({ parentId: folderId })

    // 只显示文件夹，排除待移动的文件本身
    folderList.value = response.content.filter(item =>
      item.isFolder === 1 &&
      item.id !== fileToMove.value?.id
    )
  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || '加载文件夹列表失败'
    })
  } finally {
    loading.value = false
  }
}

const navigateToRoot = () => {
  currentFolderId.value = 0
  breadcrumbList.value = []
  loadFolderList(0)
}

const navigateToFolder = (folderId: number) => {
  const index = breadcrumbList.value.findIndex(item => item.id === folderId)
  if (index >= 0) {
    breadcrumbList.value = breadcrumbList.value.slice(0, index + 1)
    currentFolderId.value = folderId
    loadFolderList(folderId)
  }
}

const goBack = () => {
  if (breadcrumbList.value.length > 0) {
    const parent = breadcrumbList.value.pop()
    currentFolderId.value = breadcrumbList.value.length > 0
      ? breadcrumbList.value[breadcrumbList.value.length - 1].id
      : 0
  } else {
    currentFolderId.value = 0
  }
  loadFolderList(currentFolderId.value)
}

const enterFolder = (folder: FileInfo) => {
  // 检查是否是禁用的文件夹
  if (folder.id === fileToMove.value?.id || folder.id === fileToMove.value?.parentId) {
    return
  }

  breadcrumbList.value.push({
    id: folder.id,
    name: folder.fileName
  })
  currentFolderId.value = folder.id
  loadFolderList(folder.id)
}

const handleMove = async () => {
  if (!fileToMove.value || !canMove.value) return

  const confirmed = await showConfirmDialog({
    title: '确认移动',
    message: `确定要将 "${fileToMove.value.fileName}" 移动到 "${getCurrentPath()}" 吗？`
  })

  if (confirmed) {
    try {
      moving.value = true
      showLoadingToast({
        message: '正在移动文件...',
        duration: 0
      })

      await moveFile(fileToMove.value.id, currentFolderId.value)

      closeToast()
      showToast({
        type: 'success',
        message: '文件移动成功'
      })

      // 刷新文件列表
      await fileStore.fetchFileList()

      // 返回文件列表
      router.back()
    } catch (error: any) {
      closeToast()
      showToast({
        type: 'fail',
        message: error.message || '移动文件失败'
      })
    } finally {
      moving.value = false
    }
  }
}

onMounted(() => {
  loadFileInfo()
  loadFolderList()
})
</script>

<style scoped>
.move-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.move-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.file-info-card {
  background: white;
  margin: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 16px 16px 0;
  border-bottom: 1px solid #ebedf0;
}

.card-header h3 {
  margin: 0 0 12px;
  font-size: 16px;
  color: #323233;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 16px;
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 16px;
  color: #323233;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #969799;
  display: flex;
  gap: 8px;
}

.target-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.section-header {
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.section-header h3 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #323233;
}

.current-path {
  font-size: 12px;
  color: #969799;
}

.breadcrumb {
  padding: 12px 16px;
  border-bottom: 1px solid #ebedf0;
  background: #f8f8f8;
}

.breadcrumb-wrapper {
  display: flex;
  align-items: center;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.breadcrumb-wrapper::-webkit-scrollbar {
  display: none;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  color: #1989fa;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.breadcrumb-item:hover {
  background-color: #f5f5f5;
}

.breadcrumb-item.active {
  color: #323233;
  cursor: default;
}

.breadcrumb-item.active:hover {
  background-color: transparent;
}

.breadcrumb-separator {
  margin: 0 4px;
  color: #969799;
  font-size: 12px;
}

.folder-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.folder-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.folder-item:hover {
  background-color: #f8f8f8;
}

.folder-item.back-item {
  color: #1989fa;
  border-bottom: 1px solid #ebedf0;
}

.folder-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.folder-item.disabled:hover {
  background-color: transparent;
}

.folder-item span {
  flex: 1;
  margin-left: 12px;
  font-size: 14px;
}

.arrow-icon {
  color: #969799;
  font-size: 12px;
}

.empty-folders {
  padding: 40px 20px;
}

.move-actions {
  padding: 16px;
  background: white;
  border-top: 1px solid #ebedf0;
}

.target-info {
  margin-bottom: 12px;
  font-size: 14px;
}

.label {
  color: #969799;
  margin-right: 8px;
}

.path {
  color: #323233;
  font-weight: 500;
}

:deep(.van-empty) {
  padding: 20px;
}
</style>